package pool

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/jinzhu/gorm"
	poolConstruct "github.com/silenceper/pool"
)

var (
	Cache map[string]poolConstruct.Pool
	Db    map[string]poolConstruct.Pool
)

func InitPool() error {
	if err := initDbPool(); err != nil {
		return err
	}

	if err := initRedisPool(); err != nil {
		return err
	}

	return nil
}

func GetDbConn(name string) (*gorm.DB, error) {
	pool, ok := Db[name]
	if !ok {
		panic(fmt.Sprintf("not found pool:%s", name))
	}

	conn, err := pool.Get()
	if err != nil {
		return nil, err
	}

	return conn.(*gorm.DB), nil
}

func PutDbConn(name string, val interface{}) error {
	pool, ok := Db[name]
	if !ok {
		panic(fmt.Sprintf("not found pool:%s", name))
	}
	return pool.Put(val)
}

func GetCacheConn(name string) (*redis.Client, error) {
	pool, ok := Cache[name]
	if !ok {
		panic(fmt.Sprintf("not found pool:%s", name))
	}

	conn, err := pool.Get()
	if err != nil {
		return nil, err
	}

	return conn.(*redis.Client), nil
}

func PutCacheConn(name string, val interface{}) error {
	pool, ok := Cache[name]
	if !ok {
		panic(fmt.Sprintf("not found pool:%s", name))
	}

	return pool.Put(val)
}
